package com.raowb.common.config;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import com.raowb.common.util.SpringBeanUtil;
import com.raowb.common.util.StringUtil;

/**
 * 
* @Description:全局配置  
* @author: RaoWenbiao
* @date 2018年8月28日
 */
public class GlobalConfig {

	private final static Logger logger = LoggerFactory.getLogger(GlobalConfig.class);

	private static ConfigurableApplicationContext context;

	private static Environment environment;
	
	
	private static Map<String,String> config = new ConcurrentHashMap<>();
	

	// 当前环境
	private static String profiles_active;

	// 是否测试或开发环境
	private static Boolean debug;
	// 时间戳，用于静态文件版本控制
	private static long timestamp = System.currentTimeMillis();

	/**
	 * 
	* @Title: debug
	* @Description: 是否为debug模式
	* @return    设定文件
	* @return boolean    返回类型
	* @throws
	 */
	public static boolean isDebug() {
		if (debug == null) {
			try {
				profiles_active = getEnvironmentProperty("spring.profiles.active");
				//System.out.println(profiles_active);
				if (profiles_active == null || !profiles_active.equals("pro")) {
					debug = true;
				} else {
					debug = false;
				}
			} catch (Exception e) {
				logger.warn(e.getMessage(), e);
				return true;
			}
		}
		return debug;
	}

	/**
	 * 
	* @Title: getTimestamp
	* @Description: 获取时间戳
	* @return    设定文件
	* @return long    返回类型
	* @throws
	 */
	public static long getTimestamp() {
		if (isDebug()) {
			return System.currentTimeMillis();
		}
		return timestamp;
	}

	public static String getEnvironmentProperty(String key) {
		return environment == null ? null : environment.getProperty(key);
	}

	public static ConfigurableApplicationContext getContext() {
		return context;
	}

	public static void setContext(ConfigurableApplicationContext context) {
		GlobalConfig.context = context;
		environment = context.getEnvironment();
	}

	public static void printBeans() {
		for (String bean : SpringBeanUtil.getApplicationContext().getBeanDefinitionNames()) {
			try {
				System.out.println(bean + ":" + SpringBeanUtil.getBean(bean).getClass());
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	
	public static String getConfig(String key){
		String value = config.get(key);
		if(value == null){
			value = getEnvironmentProperty(key);
			if(value != null){
				config.put(key,value);	
			}
			
		}		
		return value;
	}
	
	public static String getConfig(String key,String defaultValue){
		String rtn = getConfig(key);
		return  StringUtil.isBlank(rtn)?defaultValue:rtn ;
	}
	

}
